//
//  XTUtility+Keychain.m
//  XTUtilityKit
//
//  Created by Tong on 2017/6/2.
//  Copyright © 2017年 Tong. All rights reserved.
//

#import "XTUtility+Keychain.h"

@implementation XTUtility (Keychain)


/**
 保存数据到 KeyChain
 
 @param data 需要保存的数据
 @param service 指定的Service (一般使用:com.xxx.keychain 的样式)
 */
+ (void)saveData:(id)data toKeychainWithService:(NSString *)service
{
    /** 获取操作Keychain 的 Dictionary */
    NSMutableDictionary *keychainQuery = [self getKeyChainQueryWithService:service];
    
    /** 删除旧的 Item */
    SecItemDelete((__bridge CFDictionaryRef)(keychainQuery));
    
    /** 添加新的数据 */
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(__bridge id<NSCopying>)(kSecValueData)];
    
    /** 添加新 Item */
    SecItemAdd((__bridge CFDictionaryRef)(keychainQuery), NULL);
}


/**
 从 Keychain 获取保存的数据
 
 @param service 指定的Service
 @return 保存的数据
 */
+ (id)getDataFromKeychainWithService:(NSString *)service
{
    id result = nil;
    
    NSMutableDictionary *keychainQuery = [self getKeyChainQueryWithService:service];
    
    /** 设置搜索配置 */
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(__bridge id<NSCopying>)(kSecReturnData)];
    [keychainQuery setObject:(__bridge id)(kSecMatchLimitOne) forKey:(__bridge id<NSCopying>)(kSecMatchLimit)];
    
    /** 获取搜索结果 */
    CFTypeRef keyData = NULL;
    if (SecItemCopyMatching((__bridge_retained CFDictionaryRef)keychainQuery, &keyData) == noErr) {
        result = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData*)keyData];
    }
    
    if (keyData) {
        CFRelease(keyData);
    }
    
    return result;
}


/**
 删除 Keychain 数据
 
 @param service 指定的service
 */
+ (void)deleteDataInKeychainAtService:(NSString *)service
{
    NSMutableDictionary *keychainQuery = [self getKeyChainQueryWithService:service];
    SecItemDelete((__bridge CFDictionaryRef)(keychainQuery));
}

#pragma mark - Private Methods


/**
 创建一个操作Keychain 的 Dictionary

 @param service Keychain 的 Service名称
 @return NSMutableDictionary
 */
+ (NSMutableDictionary *)getKeyChainQueryWithService:(NSString *)service
{
    NSMutableDictionary *keyChainQueryDictaionary = [[NSMutableDictionary alloc]init];
   
    [keyChainQueryDictaionary setObject:(id)kSecClassGenericPassword forKey:(id)kSecClass];
    [keyChainQueryDictaionary setObject:service forKey:(id)kSecAttrService];
    [keyChainQueryDictaionary setObject:service forKey:(id)kSecAttrAccount];
  
    return keyChainQueryDictaionary;
}

@end
